package com.ztjava.auth.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;
import com.ztjava.auth.model.AuthApp;
import com.ztjava.auth.model.AuthDept;
import com.ztjava.auth.model.AuthGroup;
import com.ztjava.auth.model.AuthGroupUser;
import com.ztjava.auth.model.AuthRole;
import com.ztjava.auth.model.AuthRoleUser;
import com.ztjava.auth.model.AuthThird;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.auth.service.AuthService;
import com.ztjava.auth.validator.LoginValidator;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.annotation.CustomTemplate;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.PortalClient;
import com.ztjava.core.tool.ConfigTool;
import com.ztjava.core.tool.ExeclTool;
import com.ztjava.core.utiliy.StringUtil;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;

@ControllerClass(path = "/auth", client = PortalClient.class)
@UserController(portal = Constant.P_PORTAL)
public class AuthPortalController extends BaseController {
	private static AuthService authService = Duang.duang(AuthService.class);
	
	/***
	 * 验证码
	 */
	@Clear
	public void captcha(){
		renderCaptcha();
	}
	
	@CustomTemplate("index.html")
	public void index(){
		renderCustom();
	}

	@CustomTemplate("login.html")
	public void login() {
		renderCustom();
	}

	@Before(LoginValidator.class)
	public void doLogin() {
		AuthUser authUser = getAttr("authUser");
		AuthTool.createUserSession(authService.userToSession(authUser),
				3600 * 24, getResponse(),null);
		renderSuccess();
	}

	@UserMethod
	public void logout() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthTool.removeUserSession(authSession);
		if (Constant.XMLHttpRequest.equals(getRequest().getHeader(
				Constant.XRequestedWith))) {
			renderSuccess();
		} else {
			try {
				getResponse().sendRedirect("login");
			} catch (Exception e) {
				e.printStackTrace();
			}
			renderNull();
		}
		return;
	}

	/*************
	 * 修改Role
	 **************/
	@UserMethod("AuthRole")
	public void addEditRole() {
		Integer id = getParaToInt("id", 0);
		AuthRole authRole = new AuthRole();
		if (id > 0) {
			authRole = AuthRole.dao.findById(id);
		}
		setAttr("authRole", authRole);
		render("addEditRole.html");
	}

	@UserMethod("AuthRole")
	public void editRoleRights() {
		Integer id = getParaToInt("id", 0);
		AuthRole authRole = AuthRole.dao.findById(id);
		Cache cache = Redis.use();
		Map<String, JSONObject> map = cache.hget(Constant.R_AUTH,
				authRole.getStr("portal"));

		JSONArray menuList = new JSONArray();
		if (map != null) {
			for (String key : map.keySet()) {
				menuList.add(map.get(key));
			}
		}
		if (authRole.get("rights") != null) {
			recordChecked(menuList, authRole.getStr("rights"));
		}
		setAttr("rightsJSON", JsonKit.toJson(menuList));
		setAttr("authRole", authRole);
		render("editRoleRights.html");
	}

	/***
	 * 检查权限是否被选中
	 * 
	 * @param list
	 * @param str
	 */
	private void recordChecked(JSONArray list, String str) {
		for (int i = 0; i < list.size(); i++) {
			if (str.indexOf("," + list.getJSONObject(i).getString("rights")
					+ ",") > -1) {
				list.getJSONObject(i).put("checked", true);
				if (list.getJSONObject(i).get("children") != null) {
					recordChecked(list.getJSONObject(i)
							.getJSONArray("children"), str);
				}
			}
		}
	}

	/*************
	 * 保存Role
	 **************/
	@UserMethod("AuthRole")
	public void saveRole() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthRole authRole = getModel(AuthRole.class);
		saveModel(authRole, authSession.getId());
		renderSuccess();
	}

	/*************
	 * Role列表
	 **************/
	@UserMethod("AuthRole")
	public void roleList() {
		if (!getPara("is_ajax", "F").equals("T")) {
			render("roleList.html");
			return;
		}
		renderPageJson(authService.getRolePage(client, getParaMap()));
	}

	@UserMethod("AuthRole")
	public void editRoleUser() {
		Integer id = getParaToInt("id");
		AuthRole authRole = AuthRole.dao.findById(id);
		List<AuthUser> leftList = authService.getNotInRoleUserList(id,
				authRole.getStr("portal"), null, null);
		List<AuthUser> rightList = authService.getRoleUserList(id);
		String ids = "";
		for (int i = 0; i < rightList.size(); i++) {
			ids = ids + rightList.get(i).getInt("id");
			if (i < (rightList.size() - 1)) {
				ids = ids + ",";
			}
		}
		setAttr("id", id);
		setAttr("ids", ids);
		setAttr("leftList", leftList);
		setAttr("rightList", rightList);
		render("editRoleUser.html");
	}

	@UserMethod("AuthRole")
	public void loadNotInRoleUserList() {
		Integer id = getParaToInt("id");
		AuthRole authRole = AuthRole.dao.findById(id);
		String keyword = getPara("keyword", "");
		String ids = getPara("ids", "");
		List<AuthUser> leftList = authService.getNotInRoleUserList(id,
				authRole.getStr("portal"), keyword, ids);
		setAttr("leftList", leftList);
		setAttr(Constant.RESULT, Constant.SUCCESS);
		renderJson(new String[] { Constant.RESULT, "leftList" });
	}

	@UserMethod("AuthRole")
	public void saveRoleUser() {
		Integer id = getParaToInt("id");
		String ids = getPara("ids", "");
		if (ids.equals("")) {
			authService.deleteRoleUser(id);
		} else {
			authService.deleteRoleUserNotInStr(id, ids);
			List<AuthUser> list = authService.getStrUserNotInRole(id, ids);
			for (int i = 0; i < list.size(); i++) {
				AuthRoleUser item = new AuthRoleUser();
				item.set("user_id", list.get(i).getInt("id"));
				item.set("role_id", id);
				item.save();
			}
		}
		renderSuccess();
	}

	/*************
	 * 批量删除Role
	 **************/
	@UserMethod("AuthRole")
	public void batchDeleteRole() {
		String[] btSelectItem = getParaValues("btSelectItem");
		authService.batchDelete(AuthRole.tablename, btSelectItem);
		renderSuccess();
	}

	/*************
	 * 修改User
	 **************/
	@UserMethod("AuthUser")
	public void addEditUser() {
		Integer id = getParaToInt("id", 0);
		AuthUser authUser = new AuthUser();
		if (id > 0) {
			authUser = AuthUser.dao.findById(id);
		}else {
			authUser.set("portal", getPara("portal",Constant.P_PORTAL));
		}
		setAttr("authUser", authUser);
		render("addEditUser.html");
	}

	@UserMethod("AuthUser")
	public void reloadUserCache() {
		authService.loadUserCache();
		renderSuccess();
	}
	@UserMethod("AuthUser")
	public void loadAppCache() {
		authService.loadAppCache();
		renderSuccess();
	}

	/*************
	 * 保存User
	 **************/
	@UserMethod("AuthUser")
	public void saveUser() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthUser authUser = getModel(AuthUser.class);
		Ret ret = authService.checkRepeat(authUser, AuthUser.tablename,
				" and portal='" + authUser.getStr("portal") + "'",
				new String[] { "username", "用户名不能重复！" }, 
				new String[] { "name","姓名不能重复！" }, 
				new String[] { "phone", "手机号不能重复！" },
				new String[] { "email", "邮箱不能重复！" });
		if (ret.get(Constant.RESULT).equals(Constant.ERROR)) {
			renderRet(ret);
			return;
		}
		if (authUser.get("password") != null
				&& !authUser.getStr("password").equals("")) {
			authUser.set("password", HashKit.md5(authUser.getStr("password"))
					.toUpperCase());
		} else {
			authUser.remove("password");
		}
		saveModel(authUser, authSession.getId());
		if (authUser.get("uid") == null || authUser.getInt("uid") == 0) {
			authUser.set("uid", authUser.getInt("id") + 10000).update();
		}
		authService.loadUserCache(authUser.getInt("id"));
		renderSuccess();
	}

	@UserMethod("AuthUser")
	public void importUser() {
		render("importUser.html");
	}

	@SuppressWarnings("unchecked")
	public void doImportUser() {
		UploadFile uploadFile = getFile();
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		Ret ret = ExeclTool.execlToList(uploadFile.getFile());
		if (ret.getStr(Constant.RESULT).equals(Constant.ERROR)) {
			renderError(ret.getStr(Constant.MESSAGE));
			return;
		}
		List<Record> dataList = (List<Record>) ret.get("dataList");
		//允许密码为空，提示需要激活账户
		Ret check = ExeclTool.checkdata(dataList, 
				new String[] { "平台",ExeclTool.c_NOT_BLANK },
				new String[] { "用户名",ExeclTool.c_NOT_BLANK },
				new String[] { "姓名",ExeclTool.c_NOT_BLANK });
		if (check.getStr(Constant.RESULT).equals(Constant.ERROR)) {
			renderError(check.getStr(Constant.MESSAGE));
			return;
		}
		Map<String, Map<String, String>> repeat = new HashMap<String, Map<String, String>>();
		repeat.put("username", new HashMap<String, String>());
		repeat.put("name", new HashMap<String, String>());
		repeat.put("email", new HashMap<String, String>());
		repeat.put("phone", new HashMap<String, String>());
		List<AuthUser> userList = new ArrayList<>();
		Record record;
		for (int i = 0; i < dataList.size(); i++) {
			record = dataList.get(i);
			AuthUser authUser = new AuthUser();
			String portal = ConfigTool.basedataNameToValue("AUTH_PORTAL",record.getStr("平台"));
			if (portal == null || portal.equals("")) {
				renderError("第" + (i + 2) + "行“平台”不存在！");
				return;
			}
			authUser.set("portal", portal);

			authUser.set("username", record.getStr("用户名"));
			if (repeat.get("username").get(
					portal + "_" + authUser.getStr("username")) != null) {
				renderError("第" + (i + 2) + "行“用户名”本批次导入重复！");
				return;
			}
			repeat.get("username").put(
					portal + "_" + authUser.getStr("username"), "T");

			authUser.set("name", record.getStr("姓名"));
			if (repeat.get("name").get(portal + "_" + authUser.getStr("name")) != null) {
				renderError("第" + (i + 2) + "行“姓名”本批次导入重复！");
				return;
			}
			repeat.get("name").put(portal + "_" + authUser.getStr("name"), "T");

			authUser.set("phone", record.getStr("手机号"));
			if (authUser.get("phone") != null
					&& !authUser.get("phone").equals("")) {
				if (repeat.get("phone").get(
						portal + "_" + authUser.getStr("phone")) != null) {
					renderError("第" + (i + 2) + "行“手机号”本批次导入重复！");
					return;
				}
				repeat.get("phone").put(portal + "_" + authUser.getStr("phone"), "T");
			}
			authUser.set("email", record.getStr("邮箱"));
			if (authUser.get("email") != null
					&& !authUser.get("email").equals("")) {
				if (repeat.get("email").get(portal + "_" + authUser.getStr("email")) != null) {
					renderError("第" + (i + 2) + "行“邮箱”本批次导入重复！");
					return;
				}
				repeat.get("email").put(portal + "_" + authUser.getStr("email"), "T");
			}
			Ret authCheck = authService.checkRepeat(authUser,AuthUser.tablename,
					" and portal='" + authUser.getStr("portal") + "'",
					new String[] { "username", "第" + (i + 2) + "行用户名不能重复！" },
					new String[] { "name", "第" + (i + 2) + "行姓名不能重复！" },
					new String[] { "phone", "第" + (i + 2) + "行手机号不能重复！" },
					new String[] { "email", "第" + (i + 2) + "行邮箱不能重复！" });
			if (authCheck.getStr(Constant.RESULT).equals(Constant.ERROR)) {
				renderError(authCheck.getStr(Constant.MESSAGE));
				return;
			}
			//必须，防止为空字符串
			String password = record.getStr("密码");
			if(password!=null&&!password.equals("")){
				authUser.set("password", HashKit.md5(record.getStr("密码")).toUpperCase());
			}
			// 不管本批导入是否重复了，既然是后台，要求不高了。
			authUser.set("create_user", authSession.getId());
			userList.add(authUser);
		}
		for(int i=0;i<userList.size();i++){
			AuthUser authUser = userList.get(i);
			authUser.save();
			authUser.set("uid", authUser.getInt("id") + 10000).update();
			authService.loadUserCache(authUser.getInt("id"));
		}
		renderSuccess();
	}

	/*************
	 * User列表
	 **************/
	@UserMethod("AuthUser")
	public void userList() {
		if (!getPara("is_ajax", "F").equals("T")) {
			render("userList.html");
			return;
		}
		renderPageJson(authService.getUserPage(client, getParaMap()));
	}

	/*************
	 * 批量删除User
	 **************/
	@UserMethod("AuthUser")
	public void batchDeleteUser() {
		String[] btSelectItem = getParaValues("btSelectItem");
		authService.batchDelete(AuthUser.tablename, btSelectItem);
		renderSuccess();
	}

	@UserMethod("AuthUser")
	public void editUserRole() {
		Integer id = getParaToInt("id");
		AuthUser authUser = AuthUser.dao.findById(id);
		List<AuthRole> leftList = authService.getNotInUserRoleList(id,authUser.getStr("portal"));
		List<AuthRole> rightList = authService.getUserRoleList(id,authUser.getStr("portal"));
		String ids = "";
		for (int i = 0; i < rightList.size(); i++) {
			ids = ids + rightList.get(i).getInt("id");
			if (i < (rightList.size() - 1)) {
				ids = ids + ",";
			}
		}
		setAttr("id", id);
		setAttr("ids", ids);
		setAttr("leftList", leftList);
		setAttr("rightList", rightList);
		render("editUserRole.html");
	}

	@UserMethod("AuthUser")
	public void saveUserRole() {
		Integer id = getParaToInt("id");
		String ids = getPara("ids", "");
		authService.deleteUserRole(id);
		if (!ids.equals("")) {
			String[] arr = ids.split(",");
			for (int i = 0; i < arr.length; i++) {
				AuthRoleUser item = new AuthRoleUser();
				item.set("user_id", id);
				item.set("role_id", Integer.parseInt(arr[i]));
				item.save();
			}
		}
		renderSuccess();
	}

	@UserMethod
	public void select2LoadUserList() {
		List<AuthUser> userList = new ArrayList<>();
		String where = " where enable_flag='T'";
		String portal = getPara("portal", "");
		if (!portal.equals("")) {
			where = where + " and portal='" + portal + "'";
		}
		String keyword = getPara("keyword", "");
		if (keyword.equals("")) {
			renderJson(userList);
			return;
		}
		where = where + " and (username like '%" + keyword
				+ "%' or name like '%" + keyword + "%' ";
		if(keyword.length()>=5&&StringUtil.isNumeric(keyword)){
			where = where + " or uid="+keyword+" ";
		}
		where = where + ")";
		userList = AuthUser.dao.find("select id,(case when username is null then CONCAT(name,'(uid:',uid,')') else CONCAT(username,'(uid:',uid,')') end) as text from "
						+ AuthUser.tablename + where
						+ " order by username asc,id asc");
		renderJson(userList);
	}

	@UserMethod
	public void select2LoadDeptList() {
		List<AuthDept> deptList = new ArrayList<>();
		String where = " where enable_flag='T'";
		String portal = getPara("portal", "");
		if (!portal.equals("")) {
			where = where + " and portal='" + portal + "'";
		}
		String keyword = getPara("keyword", "");
		if (keyword.equals("")) {
			renderJson(deptList);
			return;
		}
		where = where + " and name like '%" + keyword + "%' ";
		deptList = AuthDept.dao.find("select id,name as text from "
				+ AuthDept.tablename + where + " order by id asc");
		renderJson(deptList);
	}

	@UserMethod
	public void select2LoadDeptListNum() {
		List<AuthDept> deptList = new ArrayList<>();
		String where = " where enable_flag='T'";
		String portal = getPara("portal", "");
		if (!portal.equals("")) {
			where = where + " and portal='" + portal + "'";
		}
		String keyword = getPara("keyword", "");
		if (keyword.equals("")) {
			renderJson(deptList);
			return;
		}
		where = where + " and name like '%" + keyword + "%' ";
		deptList = AuthDept.dao.find("select num as id,name as text from "
				+ AuthDept.tablename + where + " order by id asc");
		renderJson(deptList);
	}

	/*************
	 * 修改Group
	 **************/
	@UserMethod("AuthGroup")
	public void addEditGroup() {
		Integer id = getParaToInt("id", 0);
		AuthGroup authGroup = new AuthGroup();
		if (id > 0) {
			authGroup = AuthGroup.dao.findById(id);
		}
		setAttr("authGroup", authGroup);
		setAttr("userList", authService.getGroupUserList(id));
		render("addEditGroup.html");
	}

	/*************
	 * 保存Group
	 **************/
	@UserMethod("AuthGroup")
	public void saveGroup() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthGroup authGroup = getModel(AuthGroup.class);
		Ret ret = authService.checkRepeat(authGroup, AuthGroup.tablename,
				new String[] { "name", "组名不能重复！" });
		if (ret.get("result").equals("error")) {
			renderError(ret.get(Constant.MESSAGE).toString());
			return;
		}
		saveModel(authGroup, authSession.getId());

		authService.deleteGroupUser(authGroup.getInt("id"));

		String[] users = getParaValues("users");
		if (users != null) {
			List<AuthGroupUser> userList = new ArrayList<>();
			for (int i = 0; i < users.length; i++) {
				AuthGroupUser authGroupUser = new AuthGroupUser();
				authGroupUser.set("group_id", authGroup.getInt("id"));
				authGroupUser.set("user_id", users[i].trim());
				userList.add(authGroupUser);
			}
			Db.batchSave(userList, 30);
		}
		authService.updateGroupAmount(authGroup.getInt("id"));

		ConfigTool.dbToBaseData("AUTH_GROUP", AuthGroup.tablename, "id asc");
		renderSuccess();
	}

	/*************
	 * Group列表
	 **************/
	@UserMethod("AuthGroup")
	public void groupList() {
		if (!getPara("is_ajax", "F").equals("T")) {
			render("groupList.html");
			return;
		}
		renderPageJson(authService.getGroupPage(client, getParaMap()));
	}

	/*************
	 * 批量删除Group
	 **************/
	@UserMethod("AuthGroup")
	public void batchDeleteGroup() {
		String[] btSelectItem = getParaValues("btSelectItem");
		authService.batchDelete(AuthGroup.tablename, btSelectItem);

		ConfigTool.dbToBaseData("AUTH_GROUP", AuthGroup.tablename, "id asc");
		renderSuccess();
	}

	/*************
	 * 修改Dept
	 **************/
	@UserMethod("AuthDept")
	public void addEditDept() {
		Integer id = getParaToInt("id", 0);
		AuthDept authDept = new AuthDept();
		if (id > 0) {
			authDept = AuthDept.dao.findById(id);
			if (authDept.getInt("parent_id") > 0) {
				AuthDept parentDept = AuthDept.dao.findById(authDept
						.getInt("parent_id"));
				setAttr("parentDept", parentDept);
			}
		} else {
			Integer parent_id = getParaToInt("parent_id", 0);
			authDept.set("parent_id", parent_id);
			if (parent_id > 0) {
				AuthDept parentDept = AuthDept.dao.findById(parent_id);
				setAttr("parentDept", parentDept);
			}
		}
		setAttr("authDept", authDept);
		render("addEditDept.html");
	}

	/*************
	 * 保存Dept
	 **************/
	@UserMethod("AuthDept")
	public void saveDept() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthDept authDept = getModel(AuthDept.class);
		saveModel(authDept, authSession.getId());
		if (authDept.getInt("parent_id") > 0) {
			AuthDept parent = AuthDept.dao.findById(authDept
					.getInt("parent_id"));
			authDept.set("num", parent.getStr("num") + authDept.getInt("id")
					+ ",");
		} else {
			authDept.set("num", authDept.getInt("id") + ",");
		}
		authDept.update();
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "保存成功！");
		setAttr("object", authDept);

		ConfigTool.dbToBaseData("AUTH_DEPT", AuthDept.tablename, "id asc");
		ConfigTool.dbToBaseData("AUTH_DEPT_NUM",
				"select num as value,name,enable_flag from "
						+ AuthDept.tablename + " order by sort asc,id asc");
		renderJson(new String[] { Constant.RESULT, Constant.MESSAGE, "object" });
	}

	/*************
	 * Dept列表
	 **************/
	@UserMethod("AuthDept")
	public void deptList() {
		List<AuthDept> list = AuthDept.dao
				.find("select id,parent_id as pId,name from "
						+ AuthDept.tablename + " order by sort asc,id asc");
		setAttr("listJSON", JsonKit.toJson(list));
		render("deptList.html");
	}

	/*************
	 * 删除Dept
	 **************/
	@UserMethod("AuthDept")
	public void deleteDept() {
		Integer id = getParaToInt("id", 0);
		if (authService.checkDeptChild(id)) {
			renderError("存在子分类不允许删除！");
			return;
		}
		AuthDept.dao.deleteById(id);
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "删除成功！");
		setAttr("id", id);

		ConfigTool.dbToBaseData("AUTH_DEPT", AuthDept.tablename, "id asc");
		ConfigTool.dbToBaseData("AUTH_DEPT_NUM","select num as value,name,enable_flag from "+ AuthDept.tablename + " order by sort asc,id asc");

		renderJson(new String[] { Constant.RESULT, Constant.MESSAGE, "id" });
	}

	@UserMethod("AuthDept")
	public void editDeptUser() {
		Integer id = getParaToInt("id");
		AuthDept authDept = AuthDept.dao.findById(id);
		List<AuthUser> leftList = authService.getNoDeptUserList(
				authDept.getStr("portal"), null, null);
		List<AuthUser> rightList = authService.getDeptUserList(id);
		String ids = "";
		for (int i = 0; i < rightList.size(); i++) {
			ids = ids + rightList.get(i).getInt("id") + ",";
		}
		if (!ids.equals("")) {
			ids = ids.substring(0, ids.length() - 1);
		}
		setAttr("id", id);
		setAttr("ids", ids);
		setAttr("authDept", authDept);
		setAttr("leftList", leftList);
		setAttr("rightList", rightList);
		render("editDeptUser.html");
	}
	@UserMethod("AuthDept")
	public void loadDeptCache(){
		ConfigTool.dbToBaseData("AUTH_DEPT", AuthDept.tablename, "id asc");
		ConfigTool.dbToBaseData("AUTH_DEPT_NUM","select num as value,name,enable_flag from "+ AuthDept.tablename + " order by sort asc,id asc");
		renderSuccess();
	}

	@UserMethod("AuthRole")
	public void loadNotInDeptUserList() {
		Integer id = getParaToInt("id");
		AuthDept authDept = AuthDept.dao.findById(id);
		String keyword = getPara("keyword", "");
		String ids = getPara("ids", "");
		List<AuthUser> leftList = authService.getNoDeptUserList(
				authDept.getStr("portal"), keyword, ids);
		setAttr("leftList", leftList);
		setAttr(Constant.RESULT, Constant.SUCCESS);
		renderJson(new String[] { Constant.RESULT, "leftList" });
	}

	@UserMethod("AuthDept")
	public void saveDeptUser() {
		Integer id = getParaToInt("id");
		AuthDept authDept = AuthDept.dao.findById(id);
		String ids = getPara("ids", "");
		if (ids.equals("")) {
			authService.deleteUserDept(authDept.getStr("portal"), id);
		} else {
			authService.deleteUserDept(authDept.getStr("portal"), id, ids);
			authService.insertUserDept(authDept.getStr("portal"), id, ids);
		}
		renderSuccess();
	}

	/*************
	 * 修改App
	 **************/
	@UserMethod("AuthApp")
	public void addEditApp() {
		Integer id = getParaToInt("id", 0);
		AuthApp authApp = new AuthApp();
		if (id > 0) {
			authApp = AuthApp.dao.findById(id);
		}else {
			authApp.set("appid", StringUtil.getRandomString(32));
		}
		setAttr("authApp", authApp);
		render("addEditApp.html");
	}

	/*************
	 * 保存App
	 **************/
	@UserMethod("AuthApp")
	public void saveApp() {
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthApp authApp = getModel(AuthApp.class);
		Ret ret = authService.checkRepeat(authApp, AuthApp.tablename, "",new String[] { "appid", "APPID不能重复！" });
		if (ret.get(Constant.RESULT).equals(Constant.ERROR)) {
			renderError(ret.get(Constant.MESSAGE).toString());
			return;
		}
		saveModel(authApp, authSession.getId());
		
		authService.loadAppCache();
		renderSuccess();
	}

	/*************
	 * App列表
	 **************/
	@UserMethod("AuthApp")
	public void appList() {

		if (!getPara("is_ajax", "F").equals("T")) {
			keepPara();
			render("appList.html");
			return;
		}
		renderPageJson(authService.getAppPage(client, getParaMap()));

	}

	/*************
	 * 批量删除App
	 **************/
	@UserMethod("AuthApp")
	public void batchDeleteApp() {
		String[] btSelectItem = getParaValues("btSelectItem");
		authService.batchDelete(AuthApp.tablename, btSelectItem);

		authService.loadAppCache();
		renderSuccess();
	}
	/*************
	 *修改Third
	**************/
	@UserMethod("AuthThird")
	public void addEditThird(){
		Integer id = getParaToInt("id",0);
		AuthThird authThird = new AuthThird();
		if(id>0){
			authThird = AuthThird.dao.findById(id);
		}
		setAttr("authThird",authThird);
		render("addEditThird.html");
	}

	/*************
	 *保存Third
	**************/
	@UserMethod("AuthThird")
	public void saveThird(){
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		AuthThird authThird = getModel(AuthThird.class);
		saveModel(authThird,authSession.getId());
			renderSuccess();
	}

	/*************
	 *Third列表
	**************/
	@UserMethod("AuthThird")
	public void thirdList(){
		
		if(!getPara("is_ajax","F").equals("T")){
			keepPara();
			render("thirdList.html");
			return;
		}

		
		renderPageJson(authService.getThirdPage(client, getParaMap()));
	}

	/*************
	 *批量删除Third
	**************/
	@UserMethod("AuthThird")
	public void batchDeleteThird(){
		String[] btSelectItem = getParaValues("btSelectItem");
		authService.batchDelete(AuthThird.tablename, btSelectItem);
		renderSuccess();
	}

}
